package com.snail.jj.androiddemos.components;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

/**
 * Created by snail on 2017/5/10.  后台Service
 *
 * Service 必须要在既没有和任何Activity关联又处于停止状态的时候才会被销毁
 *
 * 如何销毁Service
 * a.没有bind Service
 *  1.StartService启动Service
 *  2.StopService停止Service,这样Service就销毁了
 * b.bind Service
 *  1.点击BindService后,Service也会被创建, 点击一下Unbind Service,将Activity和Service的关联解除 就会被销毁了
 *
 */

public class MyService extends Service {


    public static final String TAG = "MyService";

    private MyBinder myBinder = new MyBinder();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG,TAG + " thread is " + Thread.currentThread().getName() + Thread.currentThread().getId());
        Log.i(TAG,"onCreate");
    }

    @Override
    public int onStartCommand(Intent intent,  int flags, int startId) {
        Log.i(TAG,"onStartCommand");

        new Thread(new Runnable() {
            @Override
            public void run() {
                //开始执行后台任务
            }
        }).start();

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG,"onDestroy,清除一些不再使用的对象 防止占着内存");
    }

    /**
     * 用于和Activity通讯的方法
     *
     * @param intent
     * @return
     */
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG,"onBind");
        return myBinder;
    }

    class MyBinder extends Binder {
        public void startDownload() {
            Log.i("MyBinder","start down somethings");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //执行具体的下载任务
                }
            }).start();

        }
    }
}
